package org.shangda.wechat.pet.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.shangda.wechat.pet.config.BaseProperties;
import org.shangda.wechat.pet.dao.MemberMapper;
import org.shangda.wechat.pet.enums.EnableEnum;
import org.shangda.wechat.pet.enums.ErrorCode;
import org.shangda.wechat.pet.error.BussinessException;
import org.shangda.wechat.pet.model.Member;
import org.shangda.wechat.pet.service.*;
import org.shangda.wechat.pet.util.WxMiniappUtil;
import org.shangda.wechat.pet.web.vo.MemberSimpleInfo;
import org.shangda.wechat.pet.web.vo.MiniappMemberVo;
import com.power.common.model.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class MemberServiceImpl implements MemberService {
    @Resource
    private MemberMapper memberMapper;

    @Resource
    private BaseProperties baseProperties;

    @Resource
    private WechatMiniappService wechatMiniappService;

    @Override
    public Member findByOpenId(String openid) {
        Member member = new Member();
        member.setOpenId(openid);
        return memberMapper.selectOne(member);
    }


    @Override
    @Transactional
    public CommonResult saveMember(MiniappMemberVo miniappMemberVo){
        Member member = memberMapper.selectByPrimaryKey(miniappMemberVo.getMemberId());
        if(null == member){
            log.error("doRegister error {}", ErrorCode.LOGIN_ERROR.getMessage());
            return CommonResult.fail(ErrorCode.LOGIN_ERROR.getCode(), ErrorCode.LOGIN_ERROR.getMessage());
        }
        if(StringUtils.isNotBlank(miniappMemberVo.getMobile())) {
            member.setMobile(miniappMemberVo.getMobile().trim());
        }

        if(StringUtils.isNotBlank(miniappMemberVo.getNickname())){
            member.setNickname(miniappMemberVo.getNickname());
        }
        if(StringUtils.isNotBlank(miniappMemberVo.getCity())){
            member.setCity(miniappMemberVo.getCity());
        }
        if(StringUtils.isNotBlank(miniappMemberVo.getProvince())){
            member.setProvince(miniappMemberVo.getProvince());
        }
        if(StringUtils.isNotBlank(miniappMemberVo.getCountry())){
            member.setCountry(miniappMemberVo.getCountry());
        }

        if(StringUtils.isNotBlank(miniappMemberVo.getSurname())) { //注册会员
            member.setSurname(miniappMemberVo.getSurname().trim());
            if(StringUtils.isNotBlank(miniappMemberVo.getFirstname())) {
                member.setFirstname(miniappMemberVo.getFirstname().trim());
            }
            if(null != miniappMemberVo.getGender()) {
                member.setGender(miniappMemberVo.getGender());
            }

            String email = miniappMemberVo.getEmail();
            if(StringUtils.isNotBlank(email)){
                email = email.trim();
            }
            member.setEmail(email);
            if(null == member.getRegisterTime()) {
                member.setRegisterTime(new Date());
            }
            member.setStatus(EnableEnum.YES.getValue());
        }else { //授权信息
            if(null == member.getGender() && null != miniappMemberVo.getGender()) {
                member.setGender(miniappMemberVo.getGender());
            }
        }
        member.setUpdatedAt(new Date());
        memberMapper.updateByPrimaryKeySelective(member);
        return CommonResult.ok();
    }

    @Override
    public MiniappMemberVo getMemberInfo(MemberSimpleInfo memberSimpleInfo) {
        MiniappMemberVo miniappMemberVo = new MiniappMemberVo();
        log.info("getMemberInfo memberSimpleInfo : {}", memberSimpleInfo);
        Member member = memberMapper.selectByPrimaryKey(memberSimpleInfo.getMemberId());
        BeanUtils.copyProperties(member, miniappMemberVo);
        if(StringUtils.isNotBlank(member.getLocalHeadImgUrl())){
            miniappMemberVo.setHeadImgUrl(member.getLocalHeadImgUrl());
        }
        miniappMemberVo.setRegistered(EnableEnum.YES.getValue().equals(member.getStatus())
                || StringUtils.isNotBlank(miniappMemberVo.getSurname()));
        return miniappMemberVo;
    }

    @Override
    public void updateMemberByAuthorize(MiniappMemberVo miniappMemberVo){
        log.info("updateMemberByAuthorize miniappMemberVo : {}", miniappMemberVo);
        Member member = findByOpenId(miniappMemberVo.getOpenId());
        if(null == member){
            log.error("updateMemberByAuthorize member not exists, openId : {}", miniappMemberVo.getOpenId());
            return;
        }

        if(StringUtils.isBlank(miniappMemberVo.getMobile()) && StringUtils.isNotBlank(miniappMemberVo.getMobile())) {
            member.setMobile(miniappMemberVo.getMobile().trim());
        }

        if(null == member.getGender() && null != miniappMemberVo.getGender()) {
            member.setGender(miniappMemberVo.getGender());
        }

        if(StringUtils.isNotBlank(miniappMemberVo.getHeadImgUrl())){
            member.setHeadImgUrl(miniappMemberVo.getHeadImgUrl());
        }

        if(StringUtils.isNotBlank(miniappMemberVo.getNickname())){
            member.setNickname(miniappMemberVo.getNickname());
        }
        if(StringUtils.isNotBlank(miniappMemberVo.getCity())){
            member.setCity(miniappMemberVo.getCity());
        }
        if(StringUtils.isNotBlank(miniappMemberVo.getProvince())){
            member.setProvince(miniappMemberVo.getProvince());
        }
        if(StringUtils.isNotBlank(miniappMemberVo.getCountry())){
            member.setCountry(miniappMemberVo.getCountry());
        }
        member.setUpdatedAt(new Date());
        memberMapper.updateByPrimaryKeySelective(member);
    }



    @Override
    @Transactional
    public void memberCancellation(Integer memberId) {
        log.info("memberCancellation memberId : {}", memberId);

        if(null == memberId){
            throw new BussinessException(ErrorCode.PARAM_EMPTY);
        }
        Member member = memberMapper.selectByPrimaryKey(memberId);
        if(null == member){
            throw new BussinessException(ErrorCode.MEMBER_NOT_EXISTS);
        }
        if(EnableEnum.NO.getValue().equals(member.getStatus())){
            throw new BussinessException(ErrorCode.MEMBER_ALREADY_CANCELLATION);
        }

        //修改member状态
        member.setSurname(null);
        member.setMobile(null);
        member.setFirstname(null);
        member.setRegisterTime(null);
        member.setStatus(EnableEnum.NO.getValue());
        member.setUpdatedAt(new Date());
        memberMapper.updateByPrimaryKey(member);
    }

    @Override
    public String getUserPhoneNumber(String code) {
        log.info("getUserPhoneNumber code : {}", code);
        String accessToken = wechatMiniappService.getAccessToken(false);
        JSONObject resultJSONObject = WxMiniappUtil.getUserPhoneNumber(accessToken, code);
        return resultJSONObject.getJSONObject("phone_info").getString("phoneNumber");
    }
}
